package com.wang.springbootinit.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ExcelUtils {

    public static String excelToCsv(MultipartFile multipartFile) {
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("文件读取错误");
        }

        StringBuilder stringBuilder = new StringBuilder();
        //读取表头
        LinkedHashMap<Integer, String> headMap = (LinkedHashMap) list.get(0);
        List<String> headList = headMap.values().stream().filter(item -> ObjectUtil.isNotNull(item)).collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(headList, ",")).append("\n");

        //读取表数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap) list.get(i);
            List<String> dataList = dataMap.values().stream().filter(item -> ObjectUtil.isNotNull(item)).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataList, ",")).append("\n");
        }

        return stringBuilder.toString();
    }


    /**
     * 将excel表格数据转换为json串
     *
     * @param excelList
     * @return
     */
    public static String ExcelDataToJson(List<Map<Integer, String>> excelList) {
        /**
         * 后续可考虑字节数组，更加节省空间
         */
        return JSONUtil.toJsonStr(excelList);
    }

    /**
     * 将excel数据的json串转换为list集合形式
     *
     * @param excelDataJson
     * @return
     */
    public static List<Map<Integer, String>> JsonToExcelData(String excelDataJson) {
        JSONArray jsonArray = JSONUtil.parseArray(excelDataJson);
        List<Map> hashMapList = jsonArray.toList(Map.class);
        //将无泛型的list转换为有泛型的list
        List<Map<Integer, String>> resultList = hashMapList.stream().map(mapItem -> {
            Map<Integer, String> map = new HashMap<>();
            for (int i = 1; i <= mapItem.size(); i++) {
                String mapValue = (String) mapItem.get(1 + "");
                map.put(i, mapValue);
            }
            return map;
        }).collect(Collectors.toList());
        return resultList;
    }

}